import React, { useState } from 'react';
import { Modal, Button, Checkbox } from 'antd';
import style from './index.less';
import TRNotification from '#/utils/notification';
import { AlertResult } from '#/utils/contacts.js';
import { CloseOutlined } from '#/utils/antdIcons';
import { Input } from 'antd';
import PropTypes from 'prop-types';
import plan_icon from '@/assets/img/plan_icon.png';

const RegionModal = ({ onPress, regionData = [], selectRegion = [], code, block }) => {
  let [visible, setVisible] = useState(true);
  let [selectData, setSelectData] = useState([...selectRegion]);
  let [showData, setShowData] = useState([...regionData]);
  const _onClose = () => {
    setVisible(false);
    onPress(AlertResult.CANCEL);
  };
  const _onSubmit = () => {
    setVisible(false);
    onPress(AlertResult.SUCCESS, selectData);
  };
  const _onSearch = (value) => {
    code == 'Transaction'
      ? setShowData(regionData.filter((n) => n.provinceAllName.indexOf(value) !== -1))
      : setShowData(regionData.filter((n) => n.provinceName.indexOf(value) !== -1));
  };
  const _onClear = (isClearAll, item) => {
    if (isClearAll) {
      setSelectData([]);
    } else {
      setSelectData(selectData.filter((n) => n.provinceId !== item.provinceId));
    }
  };
  const _onCheckChange = (isCheckAll, item, checked) => {
    if (isCheckAll) {
      let arr = [];
      selectData.forEach((n) => {
        if (showData.indexOf(n) === -1) {
          arr.push(n);
        }
      });
      setSelectData(checked ? [...selectData, ...showData] : arr);
      return;
    }
    if (checked) {
      setSelectData([...selectData, item]);
    } else {
      setSelectData(selectData.filter((n) => n.provinceId !== item.provinceId));
    }
  };
  const _onGetChecked = () => {
    let flag = true;
    showData.forEach((item) => {
      if (selectData.filter((n) => n.provinceId === item.provinceId).length === 0) {
        flag = false;
      }
    });
    return flag;
  };
  const indeterminate =
    selectData.length !== showData.length && selectData.length > 0 && !_onGetChecked();
  return (
    <Modal
      centered
      closable={false}
      visible={visible}
      onCancel={_onClose}
      width={540}
      maskClosable={false}
      className="modalWraps"
      wrapClassName={style.regionModal}
      footer={[
        <Button key={'canle'} onClick={_onClose}>
          取消
        </Button>,
        <Button key={'done'} onClick={_onSubmit} type="primary">
          提交
        </Button>,
      ]}
    >
      <div className={`${style.regionModalBox} ${block ? style.regionModalBoxBlock : ''}`}>
        <div className={style.title}>
          <div className={style.titleTextBox}>
            <img src={plan_icon} alt="" />
            选择区域
          </div>
          <CloseOutlined onClick={_onClose} className={style.close} />
        </div>
        <div className={style.content}>
          <div className={style.left}>
            <div className={style.search}>
              <Input.Search placeholder="搜索" onSearch={_onSearch} allowClear />
            </div>
            <Checkbox
              indeterminate={indeterminate}
              checked={_onGetChecked()}
              onChange={(e) => {
                _onCheckChange(true, [], e.target.checked);
              }}
            >
              全选
            </Checkbox>
            <div style={{ height: '100%', overflowY: 'auto' }}>
              <div className={style.msgBox}>
                {showData &&
                  showData.map((item, index) => {
                    return (
                      <div key={index} className={style.msgItem}>
                        <Checkbox
                          onChange={(e) => _onCheckChange(false, item, e.target.checked)}
                          checked={selectData.filter((n) => n.id === item.id).length}
                        >
                          {code == 'Transaction' ? item.provinceAllName : item.provinceName}
                        </Checkbox>
                      </div>
                    );
                  })}
              </div>
            </div>
          </div>
          <div className={style.right}>
            <div className={style.rightHeader}>
              <div>已选{selectData.length || 0}项</div>
              <div className={style.clear} onClick={() => _onClear(true)}>
                清空
              </div>
            </div>
            <div style={{ height: '100%', overflowY: 'auto' }}>
              <div className={style.rightMsgBox}>
                {selectData &&
                  selectData.map((item, index) => {
                    return (
                      <div className={style.name} key={index}>
                        <CloseOutlined
                          onClick={() => _onClear(false, item)}
                          className={style.rightClose}
                        />
                        {code == 'Transaction' ? item.provinceAllName : item.provinceName}
                      </div>
                    );
                  })}
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  );
};

RegionModal.propTypes = {
  regionData: PropTypes.array,
  selectRegion: PropTypes.array,
  onPress: PropTypes.func,
  code: PropTypes.string,
};

class RelationUserModal {
  __key__ = '';
  show = ({ regionData, selectRegion, code, revenueAnalysis }) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') {
        return;
      }
      const that = this;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <RegionModal
            block={revenueAnalysis}
            code={code}
            regionData={regionData}
            selectRegion={selectRegion}
            onPress={(index, selectData) => {
              that.__key__ = '';
              resolve({ index, selectData });
            }}
          />
        ),
        duration: null,
      });
    });
  };
  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

const relationUser = new RelationUserModal();

export default relationUser;
